package com.ruoyi.common.core.utils;



import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * ip 地址获得
 *
 * @author
 * @version 1.0.1
 * @date 2019-03-06 14:32:03
 * @since 1.8
 */
public class IpAddrUtil {
    /**
     * 未知ip
     */
    private static String UNKNOWN = "unknown";
    /**
     * 内网ip
     */
    private static String LOCALHOST = "127.0.0.1";
    /**
     * ip格式
     */
    private static String IP_FORMATTER = "0:0:0:0:0:0:0:1";
    /**
     * ip地址长度
     */
    private static int IP_LEN = 15;
    /**
     * ip分隔符
     */
    private static String IP_SEPARATE_SYMBOL = ",";

    /**
     * @param request
     * @return
     * @Title: getIpAddr
     * @Description: 获得用户真实IP地址
     * @author：束文奇
     * @date 2015-8-21 上午09:53:53
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {

            ipAddress = request.getHeader("X-Real-IP");
            if (ObjectUtil.isEmpty(ipAddress)) {
                ipAddress = request.getRemoteAddr();
            }
            if (ObjectUtil.isNotEmpty(ipAddress)) {
                if (LOCALHOST.equals(ipAddress) || IP_FORMATTER.equals(ipAddress)) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
        }
        /** 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割 */
        /** "***.***.***.***".length() = 15 */
        if (ipAddress != null && ipAddress.length() > IP_LEN) {
            if (ipAddress.indexOf(IP_SEPARATE_SYMBOL) > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        System.out.println("登录IP地址:" + ipAddress);
        return ipAddress;
    }

}
